<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="表单名称" prop="formName">
        <el-input
          v-model="queryParams.formName"
          placeholder="请输入表单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['merchant:form:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['merchant:form:add']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['merchant:form:add']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="formList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" :selectable="selectable"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="针对表单类型" align="center" prop="orderType">
        <template v-slot:default="scope">
          <dict-tag :options="dict.type.form_order_type" :value="scope.row.orderType"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="表单名称" align="center" prop="formName"/>

      <el-table-column label="是否为模版表单" align="center" prop="isPublic">
        <template v-slot:default="scope">
          <el-tooltip class="item" effect="dark" content="模版表单为默认表单，所有人可见且不可更改或删除" placement="top">
          <el-switch
            v-model="scope.row.isTemplate"
            :disabled="true"
            :active-value="1"
            :inactive-value="0"
            @change="handleIsPublicChange(scope.row)"
          ></el-switch>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="isEnable">
        <template v-slot:default="scope">
          <el-switch
            v-model="scope.row.isEnable"
            :disabled="scope.row.isTemplate==1"
            :active-value="true"
            :inactive-value="false"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['merchant:form:add']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            :disabled="scope.row.isTemplate==1"
            v-hasPermi="['merchant:form:add']"
          >修改
          </el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-if="scope.row.orderType==0"
                :disabled="rentalForm==scope.row.id"
                command="handleRentalForm"
                icon="el-icon-collection"
              >指定租车订单送车提成/报销模版
              </el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.orderType==1"
                :disabled="collectForm==scope.row.id"
                command="handleCollectForm"
                icon="el-icon-collection"
              >指定租车订单收车提成/报销模版
              </el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.orderType==2"
                :disabled="charterForm==scope.row.id"
                command="handleCharterForm"
                icon="el-icon-collection"
              >指定包车订单提成/报销模版
              </el-dropdown-item>
              <el-dropdown-item
                command="handleDelete"
                icon="el-icon-delete"
                v-if="!scope.row.isTemplate==1"
                v-hasPermi="['merchant:form:add']"
              >删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生成员工提成及报销模版表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="表单名称" prop="formName">
          <span slot="label">
            表单名称
            <el-tooltip content="用于表单模版的命名，表单用于员工提交的提成和报销信息" placement="top">
              <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-input v-model="form.formName" placeholder="请输入表单名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织架构" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true"
                          placeholder="请选择对应组织架构"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单表类型" prop="orderType">
          <span slot="label">
            表单类型
            <el-tooltip content="表单在订单中哪种类型的订单中使用" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
              <el-select v-model="form.orderType" placeholder="表单适用类型">
                <el-option v-for="dict in dict.type.form_order_type"
                           :key="dict.value"
                           :label="dict.label"
                           :value="Number(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12" style="margin-bottom: 12px">-->
<!--            <el-form-item label="公有">-->
<!--              <span slot="label">-->
<!--            所有可见-->
<!--            <el-tooltip content="将会是所有门店用户可见的表单模版" placement="top">-->
<!--              <i class="el-icon-question"></i>-->
<!--                </el-tooltip>-->
<!--              </span>-->
<!--              <el-switch v-model="form.isPublic" :active-value="true"-->
<!--                         :inactive-value="false" ></el-switch>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>

        <el-divider content-position="center">生成单时出现的选项信息信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWxFormItem">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWxFormItem">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="wxFormItemList" :row-class-name="rowWxFormItemIndex"
                  @selection-change="handleWxFormItemSelectionChange" ref="wxFormItem">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="标签名称" prop="itemLabel">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemLabel" placeholder="请输入标签名称"/>
            </template>
          </el-table-column>
          <el-table-column label="选项类型" prop="itemType">
            <template slot-scope="scope">
              <el-select v-model="scope.row.itemType" placeholder="请选择选项类型">
                <el-option v-for="dict in dict.type.form_item_type" :key="dict.value"
                           :label="dict.label"
                           :value="Number(dict.value)"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="处理类型" prop="handleFlag">
            <template slot-scope="scope">
              <el-select v-model="scope.row.handleFlag"
                         placeholder="请输入处理标记方式,定义字典handle_flag，”commission“为需要进行提成计算标识，“reimbursement”为报销费用。”ordnay“为只会记录，不做处理">
                <el-option v-for="dict in dict.type.form_item_flag" :key="dict.value"
                           :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="生成表单" :visible.sync="openView" min-width="500px" max-width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :md="10" :sm="12" v-for="item in wxFormItemList">
            <el-form-item :label="item.itemLabel">
              <el-input :value="item.value" v-if="item.itemType==1" disabled></el-input>
              <el-input-number :precision="2" :value="item.value" v-if="item.itemType==2" step-strictly
                               disabled></el-input-number>
              <el-input v-model="item.value" type="textarea" v-if="item.itemType==3" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {addForm, delForm, getForm, listForm, updateForm, updateOnlyForm} from "@/api/merchant/form";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {deptTreeSelect} from "@/api/system/user";
import {listVehcusunit, updateVehcusunit} from "@/api/merunit/vehmerunit";
import {Message} from "element-ui";

export default {
  name: "Form",
  components: {Treeselect},
  dicts: ['form_item_type', 'form_order_type', 'form_item_flag'],
  data() {
    return {
      rentalForm: '',
      charterForm: '',
      collectForm:'',
      unitId: '',
      // 部门树选项
      deptOptions: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWxFormItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生成员工提成及报销模版表表格数据
      formList: [],
      // 生成单时出现的选项信息表格数据
      wxFormItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查看生成界面
      openView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderType: null,
        formName: null,
        deptId: null,
        isPublic: null,
        isEnable: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderType: [
          {required: true, message: "针对订单类型生成的表单不能为空", trigger: "change"}
        ],
        formName: [
          {required: true, message: "表单名称不能为空", trigger: "blur"}
        ],
        deptId: [
          {
            required: true,
            message: "组织架构id，设计组织架构分为根节点平台，二级节点商户，三级节点门店。此处存储为二级组织架构节点，保证表单可看不能为空",
            trigger: "blur"
          }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.init()
  },
  methods: {
    selectable(row, index) {
      return row.isTemplate != 1
    },
    handleCharterForm(row) {
      this.$modal.confirm('是否确认删除生成员工提成及报销模版表编号为"' + row.id + '"的数据项？').then(() => {
        return updateVehcusunit({
          id: this.unitId,
          charterForm: row.id
        });
      }).then(() => {
        this.init();
        Message.success('修改成功')
      }).catch(() => {
      });
    },
    handleCollectForm(row){
      this.$modal.confirm('是否确认租车订单收车员工提成及报销使用表单"' + row.id + '"的数据项？').then(() => {
        return updateVehcusunit({
          id: this.unitId,
          collectForm: row.id
        });
      }).then(() => {
        this.init();
        Message.success('修改成功')
      }).catch(() => {
      });
    },
    handleRentalForm(row) {
      this.$modal.confirm('是否确认租车订单送车员工提成及报销使用表单"' + row.id + '"的数据项？').then(() => {
        return updateVehcusunit({
          id: this.unitId,
          rentalForm: row.id
        });
      }).then(() => {
        this.init();
        Message.success('修改成功')
      }).catch(() => {
      });

    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "handleCharterForm":
          this.handleCharterForm(row);
          break;
        case "handleRentalForm":
          this.handleRentalForm(row);
          break
        case "handleCollectForm":
          this.handleCollectForm(row);
        default:
          break;
      }
    },
    handleStatusChange(row) {
      let text = row.isEnable === true ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.formName + '"表单吗吗？').then(function () {
        return updateOnlyForm({
          id: row.id, isEnable: row.isEnable
        });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.isEnable = row.isEnable === false;
      });
    },
    handleIsPublicChange(row) {
      let text = row.isPublic === true ? "公开" : "停止公开";
      this.$modal.confirm('确认要"' + text + '""' + row.formName + '"表单吗吗？').then(function () {
        return updateOnlyForm({
          id: row.id, isPublic: row.isPublic
        });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.isPublic = row.isPublic === false;
      });
    },
    init() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
      listVehcusunit().then(response=>{
        if (response.code==200){
          console.log('rentalForm', response.rows[0].rentalForm)
          console.log('charterForm:', response.rows[0].charterForm)
          this.charterForm = response.rows[0].charterForm
          this.rentalForm = response.rows[0].rentalForm
          this.collectForm=response.rows[0].collectForm
          this.unitId = response.rows[0].id

        }
      })
    },
    /** 查询生成员工提成及报销模版表列表 */
    getList() {
      this.loading = true;
      listForm(this.queryParams).then(response => {
        this.formList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderType: null,
        formName: null,
        deptId: null,
        isPublic: null,
        isEnable: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null
      };
      this.wxFormItemList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生成员工提成及报销模版表";
    },
    handleView(row) {
      getForm(row.id).then(response => {
        //this.form = response.data;
        this.wxFormItemList = response.data.wxFormItemList;
        this.openView = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getForm(id).then(response => {
        this.form = response.data;
        this.wxFormItemList = response.data.wxFormItemList;
        this.open = true;
        this.title = "修改生成员工提成及报销模版表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.wxFormItemList = this.wxFormItemList;
          if (this.form.id != null) {
            updateForm(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addForm(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除生成员工提成及报销模版表编号为"' + ids + '"的数据项？').then(function () {
        return delForm(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 生成单时出现的选项信息序号 */
    rowWxFormItemIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 生成单时出现的选项信息添加按钮操作 */
    handleAddWxFormItem() {
      let obj = {};
      obj.itemLabel = "";
      obj.itemType = "";
      obj.handleFlag = "";
      this.wxFormItemList.push(obj);
    },
    /** 生成单时出现的选项信息删除按钮操作 */
    handleDeleteWxFormItem() {
      if (this.checkedWxFormItem.length == 0) {
        this.$modal.msgError("请先选择要删除的生成单时出现的选项信息数据");
      } else {
        const wxFormItemList = this.wxFormItemList;
        const checkedWxFormItem = this.checkedWxFormItem;
        this.wxFormItemList = wxFormItemList.filter(function (item) {
          return checkedWxFormItem.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleWxFormItemSelectionChange(selection) {
      this.checkedWxFormItem = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('merchant/form/export', {
        ...this.queryParams
      }, `form_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
